﻿using System.IO;
using System.Xml.Linq;
using DocumentFormat.OpenXml.Packaging;

namespace Songhay.OpenXml
{
    using Songhay.OpenXml.Models;
    using Songhay.Xml;

    public static partial class OpenXmlUtility
    {
        /// <summary>
        /// Writes the HTML file.
        /// </summary>
        /// <param name="inputPathToWordDocument">The input path to Word document.</param>
        /// <param name="outputPathToHtmlFile">The output path to HTML file.</param>
        /// <param name="settings">The settings.</param>
        public static void WriteHtmlFile(string inputPathToWordDocument, string outputPathToHtmlFile, SonghayHtmlConverterSettings settings)
        {
            // This example shows the simplest conversion. No images are converted.
            // A cascading style sheet is not used.
            byte[] byteArray = File.ReadAllBytes(inputPathToWordDocument);
            using(MemoryStream memoryStream = new MemoryStream())
            {
                memoryStream.Write(byteArray, 0, byteArray.Length);
                using(WordprocessingDocument doc = WordprocessingDocument.Open(memoryStream, true))
                {
                    XElement xhtml = OpenXmlUtility.TransformOpcToHtml(doc, settings);

                    // Note: the XHTML returned by TransformPackage contains objects of type
                    // XEntity. PtOpenXmlUtil.cs defines the XEntity class. See
                    // http://blogs.msdn.com/ericwhite/archive/2010/01/21/writing-entity-references-using-linq-to-xml.aspx
                    // for detailed explanation.
                    //
                    // If you further transform the XML tree returned by TransformPackage, you
                    // must do it correctly, or entities do not serialize properly.

                    var encoding = settings.UseEntityMap ? XEncoding.Windows1252 : XEncoding.Utf08;
                    var document = new XDocument(
                        XObjectUtility.GetXDeclaration(encoding:encoding, isStandAlone:true),
                        XObjectUtility.XhtmlDocTypeTransitional, xhtml);
                    document.Save(outputPathToHtmlFile, SaveOptions.OmitDuplicateNamespaces);
                }
            }
        }
    }
}
